<?php
/**
 * crcl/base
 *
 * Copyright 2013 CRCL - André Sabosch - info@crcl.de
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

 /**
 * Console specific methods
 */

namespace crcl\base;

interface IConsole
{
  /**
   * Is PHP running on cli mode?
   *
   * @static
   * @return  bool
   */
  public static function isCli();

  /**
   * Returns param
   * @example php index.php --call test -> Console::getParam('call) = test
   *
   * @static
   * @param string  $sParam
   * @return  string
   */
}

class Console implements IConsole
{
  public static function isCli()
  {
    if (\php_sapi_name() == 'cli')
    {
      return \TRUE;
    }
    // no code coverage analysis: will never be executed on unittests (CLI :)
    // @codeCoverageIgnoreStart
    return \FALSE;
    // @codeCoverageIgnoreEnd
  }

  public static function getParam($sParam)
  {
    if (isset($GLOBALS['argv']))
    {
      $sResult = self::searchParam(String::getInstance($sParam)->doStartWith('-'));
      if ($sResult === \FALSE)
      {
        $sResult = self::searchParam(String::getInstance($sParam)->doStartWith('--'));
      }
      if ($sResult !== \FALSE)
      {
        return $sResult;
      }
    }
    else
    {
      throw new console\Exception(
        'No arguments',
        console\Exception::ERROR_NOARGS,
        array('param' => $sParam));
    }
    throw new console\Exception(
      'Invalid param',
      console\Exception::ERROR_INVALIDPARAM,
      array('param' => $sParam, 'argv' => $GLOBALS['argv'], 'argc' => $GLOBALS['argc']));
  }

  /** PRIVATE *************************************************************************************/

  private static function searchParam($sParam)
  {
    $iSearch = \array_search($sParam, $GLOBALS['argv']);
    if ($iSearch !== \FALSE)
    {
      $iSearchPos = $iSearch+1;
      if (isset($GLOBALS['argv'][$iSearchPos]))
      {
        return $GLOBALS['argv'][$iSearchPos];
      }
      return '';
    }
    return \FALSE;
  }
}
